package com.example.demo5.info.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo5.info.mapper.MenuMapper;
import com.example.demo5.info.pojo.Menu;
import com.example.demo5.info.service.MenuService;
import com.example.demo5.result.AjaxResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper,Menu> implements MenuService {
    @Resource
    private MenuMapper menuMapper;
    //查询列表的方法
    @Override
    public AjaxResult getList(Menu menu) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //条件查找
        List<Menu> menus=menuMapper.selectList(queryWrapper);
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //设置你的需要树结构表的id字段实体类
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("pid");
//        设置最大子集
//        treeNodeConfig.setDeep(3);
        List<Tree<String>> build = TreeUtil.build(menus, "0", treeNodeConfig,
                //这里的menu是你的menu对象 tree就是树对象
                (item, tree) -> {
                    //开始处理数据
                    tree.setId(String.valueOf(item.getId()));
                    tree.setParentId(item.getPid());
                    tree.setName(item.getName());
                    tree.putExtra("path" ,item.getPath());
                    tree.putExtra("title" ,item.getTitle());
                    tree.putExtra("icon" ,item.getIcon());
                    tree.putExtra("url" ,item.getUrl());
                });
        return AjaxResult.success(build);

    }
    //新增列表的方法
    @Override
    public AjaxResult setList(Menu menu) {
        String newMenuTitle=menu.getName();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",newMenuTitle);
        List<Menu> menus=menuMapper.selectList(queryWrapper);
        if(menus.size()>0){
            return AjaxResult.error("菜单已存在");
        }
        menu.setUrl(menu.getPath());
        menu.setName(menu.getTitle());
        menuMapper.insert(menu);
        return AjaxResult.success("添加成功");
    }
    //删除方法
    @Override
    public AjaxResult delete(long id) {
        return AjaxResult.success(menuMapper.deleteById(id));
    }
    //修改的方法
    @Override
    public AjaxResult modify(Menu menu) {
        return AjaxResult.success(menuMapper.updateById(menu));
    }

    @Override
    public AjaxResult queryId(Menu menu) {
        int id=menu.getId();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        List<Menu> menus=menuMapper.selectList(queryWrapper);
        return AjaxResult.success(menus.get(0));
    }
};
